package
{
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.utils.getTimer;
	
	public class CacheTest extends Sprite
	{
		private var logger:TextField = new TextField();
		
		private function row(...cols):void
		{
			logger.appendText(cols.join(",") + "\n");
		}
		
		public function CacheTest()
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			logger.autoSize = TextFieldAutoSize.LEFT;
			addChild(logger);
			
			testVector();
			row();
			testBitmapData();
		}
		
		private function testVector():void
		{
			const SIZE:int = 10000000;
			var beforeTime:int;
			var afterTime:int;
			var i:int;
			var sum:int;
			
			// Build vectors of indices
			var inOrder:Vector.<int> = new Vector.<int>(SIZE);
			for (i = 0; i < SIZE; ++i)
			{
				inOrder[i] = i;
			}
			var randomOrder:Vector.<int> = inOrder.slice();
			shuffle(randomOrder);
			row("Vector Access", "Time");
			sum = 0;
			beforeTime = getTimer();
			for (i = 0; i < SIZE; ++i)
			{
				sum += inOrder[inOrder[i]];
			}
			afterTime = getTimer();
			row("Sequential", (afterTime-beforeTime));
			sum = 0;
			beforeTime = getTimer();
			for (i = 0; i < SIZE; ++i)
			{
				sum += randomOrder[randomOrder[i]];
			}
			afterTime = getTimer();
			row("Random", (afterTime-beforeTime));
		}
		
		private function testBitmapData():void
		{
			var SIZE:int = 2048;
			var bmd:BitmapData = new BitmapData(SIZE, SIZE, true, 0xff123456);
			var curRow:int;
			var curCol:int;
			var sum:int;
			var beforeTime:int;
			var afterTime:int;
			
			row("BitmapData Outer Loop", "Time");
			
			sum = 0;
			beforeTime = getTimer();
			for (curRow = 0; curRow < SIZE; ++curRow)
			{
				for (curCol = 0; curCol < SIZE; ++curCol)
				{
					sum += bmd.getPixel32(curCol, curRow);
				}
			}
			afterTime = getTimer();
			row("Row", (afterTime-beforeTime));
			
			sum = 0;
			beforeTime = getTimer();
			for (curCol = 0; curCol < SIZE; ++curCol)
			{
				for (curRow = 0; curRow < SIZE; ++curRow)
				{
					sum += bmd.getPixel32(curCol, curRow);
				}
			}
			afterTime = getTimer();
			row("Col", (afterTime-beforeTime));
		}
		
		private function shuffle(vec:Vector.<int>):void
		{
			var len:uint = vec.length;
			while (len)
			{
				var index:uint = Math.floor(Math.random() * len);
				len--;
				
				var temp:int = vec[len];
				vec[len] = vec[index];
				vec[index] = temp;
			}
		}
	}
}